package com.tomatozq163;

import java.awt.*;
import java.awt.event.*;

public class AlgoVisualizer {
    private Circle[] circles;
    private AlgoFrame frame;
    private boolean isAnimated = true;

    public AlgoVisualizer(int sceneWidth,int sceneHeight,int N){
        circles = new Circle[N];
        int R = 50;

        for (int i = 0; i < N; i++) {
            int x = R + (int)(Math.random()*(sceneWidth - 2*R));
            int y = R + (int)(Math.random()*(sceneHeight - 2*R));
            int vx = (int)(Math.random()*11) - 5;
            int vy = (int)(Math.random()*11) - 5;

            circles[i] = new Circle(x,y,R,vx,vy);
        }

//        circles = new Circle[1];
//        circles[0] = new Circle(sceneWidth - R,sceneHeight - R,R,0,0);

        EventQueue.invokeLater(()->{
            frame = new AlgoFrame("Welcome",sceneWidth,sceneHeight);

            frame.addKeyListener(new AlgoKeyListener());
            frame.addMouseListener(new AlgoMouseListener());

            new Thread(()->{
                run();
            }).start();
        });
    }

    private void run(){
        while(true){
            //绘制数据
            frame.render(circles);
            AlgoVisHelper.pause(20);

            //更新数据
            if (isAnimated){
                for (Circle circle : circles){
                    circle.move(0,frame.getCanvasWidth(),0,frame.getCanvasHeight());
                }
            }
        }
    }

    private class AlgoKeyListener extends KeyAdapter {
        @Override
        public void keyReleased(KeyEvent event) {
            super.keyReleased(event);

            if (event.getKeyChar() == ' '){
                isAnimated = !isAnimated;
            }
        }
    }

    private class AlgoMouseListener extends MouseAdapter{
        @Override
        public void mousePressed(MouseEvent event) {
            super.mousePressed(event);

            //排除菜单栏高度
            event.translatePoint(0,-(frame.getBounds().height - frame.getCanvasHeight()));
//            System.out.println(event.getPoint())

            for (Circle circle :  circles) {
                if(circle.contain(event.getPoint())){
                    circle.isFilled = !circle.isFilled;
                }
            }
        }
    }

    public static void main(String[] args) {
        // write your code here
        int sceneWidth = 800;
        int sceneHeight = 600;

        int N = 10;

        AlgoVisualizer visualizer = new AlgoVisualizer(sceneWidth,sceneHeight,N);

    }
}
